//使用require.context
//1. 一个要搜索的目录
//2. 一个标记表示是否还要搜索其子目录。



//3. 一个匹配文件的正则表达式。
let files = require.context("../pages",true,/\.vue$/)

// console.log(files.keys())

let repeatRoutes = files.keys().map(path=> {
    // console.log(files(path))
    let regExp = /(\/index\.vue|\.vue)$/
    let com = files(path).default;
    path = path.replace(regExp, "").substring(1)
    // console.log(path)
    // console.log(com.meta)
    return{
        redirect: com.redirect??null,
        name:com.name?? path.substring(1).split("/").join("-"),
        meta: com.meta ?? {}, //路由元信息
        path:path.toLowerCase(),
        component: ()=>import("@/pages"+path)
    }
});

// console.log(repeatRoutes)

// export default repeatRoutes;

const convertTree = (repeatRoutes)=>{
    //每条数据加id，如果是嵌套路由则加上pid
    let treeRoutes = [];

    //遍历repeatRoutes 对数据的id进行处理

    repeatRoutes.forEach(route => {
        let pathArr = route.path.substring(1).split('/')
        route.id = pathArr.join("-")
        // console.log(pathArr)
        //如果数组的长度大于1，说明是子路由，要添加pid
        if(pathArr.length > 1){
           let pidArr = [...pathArr] //浅拷贝
           pidArr.pop()
           route.pid = pidArr.join("-")

        }
        // console.log(route)
    })
    repeatRoutes.forEach(route => {
        let parent =repeatRoutes.find(v=>v.id === route.pid)
        // console.log(parent)
        if(parent){
            if(!parent.children){
                parent.children = []
            }
            route.path = route.path.split("/").pop()
            parent.children.push(route)
        }else{
            treeRoutes.push(route)
        }
    })
    return treeRoutes
}

let result = convertTree(repeatRoutes)
console.log(result)

export default result